import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 保留历史记录
    history: ["玄幻", "修仙", "剑来", "雪中"],
    // 书架书籍
    bookList: [
      {
        id: "bd_cf0f8610e1b44acb96a209ea07b8af85_4",
        author: "烽火戏诸侯",
        cover: "https://easyreadfs.nosdn.127.net/HQK1f-egGwi6nbXpMbJCOg==/8796093025075467512",
        title: "剑来",
      },
      {
        id: "bd_3835a38a99254f6da801c47d3cc4b377_4",
        author: "火星引力",
        cover: "https://easyreadfs.nosdn.127.net/H_-x9cZErXoNV-R3T5rpXQ==/8796093024995190498",
        title: "逆天邪神",
      }
    ],
    readHistory: [
      {
        id: "bd_cf0f8610e1b44acb96a209ea07b8af85_4",
        author: "烽火戏诸侯",
        cover: "https://easyreadfs.nosdn.127.net/HQK1f-egGwi6nbXpMbJCOg==/8796093025075467512",
        title: "剑来",
      },
      {
        id: "bd_3835a38a99254f6da801c47d3cc4b377_4",
        author: "火星引力",
        cover: "https://easyreadfs.nosdn.127.net/H_-x9cZErXoNV-R3T5rpXQ==/8796093024995190498",
        title: "逆天邪神",
      }
    ],

  },
  mutations: {
    // 添加搜索历史
    addHistory(state, key) {
      console.log("vuex接收到的key值===>", key);
      if (state.history.indexOf(key) == -1) {
        state.history.push(key);
      }
    },
    //  删除历史记录
    delHistory(state) {
      state.history = [];
    },
    //  添加进入书架
    addrack(state, obj) {
      // 没有数据就加入
      console.log(obj.id);
      state.bookList.forEach(item => {
        console.log(item.id);
      })
      if (state.bookList.findIndex(_ => _.id == obj.id) == -1) {
        console.log("加入书架");
        state.bookList.push(obj);
      }
    },
    //  删除书架内的数据
    removerack(state, obj) {
      // 裁切数组
      if (state.bookList.findIndex(item => item.id == obj.id) != -1) {
        console.log("移出书架");
        let index = state.bookList.findIndex(_ => _.id == obj.id)
        state.bookList.splice(index, 1);
      }
    },
    sethistory(state, obj) {
      if (state.readHistory.findIndex(_ => _.id == obj.id) !== -1) {
        let index = state.readHistory.findIndex(_ => _.id == obj.id)
        state.readHistory.splice(index, 1)
        state.readHistory.unshift(obj)
      } else {
        state.readHistory.unshift(obj)
      }
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [createPersistedState()]
})
